﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZDSoft.TES.Entity.SystemEntity;
using ZDSoft.TES.Manager.SystemManager;
using ZDSoft.TES.Service.SystemService;

namespace ZDSoft.TES.Component.SystemComponent
{
    public class OrganizationComponent : ComponentBase<Organization, OrganizationManager>, IOrganizationService
    {
        public int Create(string id, string pid, string name)
        {
            Organization organization = new Organization();
            IList<Organization> sType = base.FindAll();
            bool flag = true;
            for (int i = 0; i < sType.Count; i++)
            {
                if (sType[i].ID == int.Parse(id))
                {

                    flag = false;
                    break;
                }
            }
            if (flag == true)
            {
                organization.OrganizationName = name;
                if (pid != "")
                {
                    organization.Parent = base.FindByID(int.Parse(pid));
                }
                organization.IsActive = true;
                base.Create(organization);

            }
            else
            {
                organization = FindByID(int.Parse(id));
                organization.OrganizationName = name;
                base.Update(organization);
            }

            return organization.ID;
        }

        IList<Organization> leafNode = new List<Organization>();
        public IList<Organization> FindOrganizationLeaves()
        {

            FindLeafeNode(base.FindAll().Where(o => o.Parent == null).First());
            return leafNode;
        }


        private void FindLeafeNode(Organization organization)
        {
            if (organization.Children == null || organization.Children.Count == 0)
            {
                leafNode.Add(organization);
            }
            else
            {
                foreach (Organization sType in organization.Children)
                {
                    FindLeafeNode(sType);
                }
            }
        }

        public IList<Organization> FindOrganizationParents()
        {
            IList<Organization> siTypeList = base.FindAll();
            IList<Organization> parents = new List<Organization>();
            for (int i = 0; i < siTypeList.Count; i++)
            {
                if (siTypeList[i].Parent == null)
                {
                    parents.Add(siTypeList[i]);
                }
            }

            return parents;
        }
    }
}

